"use client";
import React, { useState, useRef } from "react";
import { PageContainer, ProTable } from "@ant-design/pro-components";
import type { ProColumns, ActionType } from "@ant-design/pro-components";
import { Button, Form, Input, Modal, Select, message, Space, Tag } from "antd";
import { listQuestionBankByPageUsingPost } from "@/api/questionBankController";
import {
  listMultiByPageUsingPost,
  MultiQuestionAddRequest,
  MultiQuestionUpdateRequest,
  MultiQuestionDeleteRequest,
} from "@/api/mutliQuestionController";
import { PlusOutlined } from "@ant-design/icons";
import MultiQuestion = API.MultiQuestion;
import dayjs from "dayjs";

interface Question {
  id: string;
  question: string;
  questionBankId: number;
  subject: string;
  answerA: string;
  answerB: string;
  answerC: string;
  answerD: string;
  rightAnswer: string;
  analysis: string;
  score: number;
  level: number;
  createTime?: string;
}

interface QuestionBank {
  id: number;
  title: string;
}

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const OnlineQuestionAdminPage: React.FC = () => {
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [questionBanks, setQuestionBanks] = useState<QuestionBank[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [currentQuestion, setCurrentQuestion] = useState<Question | null>(null);

  // 加载题库数据
  const loadQuestionBanks = async () => {
    try {
      const res = await listQuestionBankByPageUsingPost({
        current: 1,
        pageSize: 1000,
      });
      // @ts-ignore
      if (res.code === 0 && res.data?.records) {
        // @ts-ignore
        setQuestionBanks(res.data.records);
      }
    } catch (error) {
      message.error("题库加载失败");
    }
  };

  // 显示新建对话框
  const showCreateModal = async () => {
    await loadQuestionBanks();
    setCreateModalVisible(true);
  };

  // 显示编辑对话框
  const showEditModal = async (record: Question) => {
    await loadQuestionBanks();
    setCurrentQuestion(record);
    editForm.setFieldsValue({
      ...record,
      questionBankId: record.questionBankId,
      rightAnswer: record.rightAnswer.toUpperCase(),
      level: record.level.toString(),
      score: record.score.toString(),
    });
    setEditModalVisible(true);
  };

  // 处理新建提交
  const handleCreate = async () => {
    try {
      const values = await createForm.validateFields();
      setSubmitting(true);
      const selectedBank = questionBanks.find(
        (bank) => bank.id === values.questionBankId,
      );

      const params: MultiQuestion = {
        ...values,
        score: Number(values.score),
        level: Number(values.level),
        questionBankId: values.questionBankId,
        subject: selectedBank?.title || "",
      };

      const res = await MultiQuestionAddRequest(params);
      // @ts-ignore
      if (res.code === 0) {
        message.success("新增成功");
        setCreateModalVisible(false);
        createForm.resetFields();
        actionRef.current?.reload();
      }
    } catch (error) {
      console.error("新增失败:", error);
      message.error("新增失败");
    } finally {
      setSubmitting(false);
    }
  };

  // 新增删除处理函数
  const handleDelete = async (record: Question) => {
    Modal.confirm({
      title: "确认删除题目",
      content: `确定要删除该题目吗？`,
      okText: "确认",
      okType: "danger",
      cancelText: "取消",
      onOk: async () => {
        try {
          const res = await MultiQuestionDeleteRequest({
            // @ts-ignore
            multiQuestionId: record.id,
          });
          // @ts-ignore
          if (res.code === 0) {
            message.success("删除成功");
            actionRef.current?.reload();
          }
        } catch (error) {
          console.error("删除失败:", error);
          message.error("删除失败");
        }
      },
    });
  };

  // 处理编辑提交
  const handleEdit = async () => {
    try {
      const values = await editForm.validateFields();
      setSubmitting(true);
      const selectedBank = questionBanks.find(
        (bank) => bank.id === values.questionBankId,
      );

      const params: MultiQuestion = {
        ...values,
        id: currentQuestion?.id,
        score: Number(values.score),
        level: Number(values.level),
        questionBankId: values.questionBankId,
        subject: selectedBank?.title || "",
      };

      const res = await MultiQuestionUpdateRequest(params);

      // @ts-ignore
      if (res.code === 0) {
        message.success("更新成功");
        setEditModalVisible(false);
        editForm.resetFields();
        actionRef.current?.reload();
      }
    } catch (error) {
      console.error("更新失败:", error);
      message.error("更新失败");
    } finally {
      setSubmitting(false);
    }
  };

  // 时间格式化
  const timestampToDate = (timestamp: string) => {
    const date = new Date(timestamp);
    return date.toLocaleString();
  };

  // 列配置
  const columns: ProColumns<Question>[] = [
    {
      title: "题目ID",
      dataIndex: "id",
      key: "id",
      search: false,
      hideInForm: true,
    },
    {
      title: "题目内容",
      dataIndex: "question",
      key: "question",
      width: 240,
      search: {
        transform: (value) => ({ question: value }),
      },
    },
    {
      title: "所属题库",
      dataIndex: "questionBankId",
      key: "questionBankId",
      valueType: "select",
      width: 280,
      fieldProps: {
        showSearch: true,
        placeholder: "请选择题库",
      },
      request: async () => {
        try {
          const res = await listQuestionBankByPageUsingPost({
            current: 1,
            pageSize: 1000,
          });
          // @ts-ignore
          if (res.code === 0 && res.data) {
            // @ts-ignore
            return res.data.records.map((item: any) => ({
              label: item.title,
              value: item.id,
            }));
          }
          return [];
        } catch (error) {
          message.error("题库加载失败");
          return [];
        }
      },
      search: {
        transform: (value) => ({ questionBankId: value }),
      },
    },
    {
      title: "答案A",
      dataIndex: "answerA",
      key: "answerA",
      search: false,
      width: 240,
    },
    {
      title: "答案B",
      dataIndex: "answerB",
      key: "answerB",
      search: false,
      width: 240,
    },
    {
      title: "答案C",
      dataIndex: "answerC",
      key: "answerC",
      search: false,
      width: 240,
    },
    {
      title: "答案D",
      dataIndex: "answerD",
      key: "answerD",
      search: false,
      width: 240,
    },
    {
      title: "正确答案",
      dataIndex: "rightAnswer",
      key: "rightAnswer",
      width: 240,
      search: false,
      align: "center",
      render: (text) => <span style={{ color: "#52c41a" }}>选项 {text}</span>,
    },
    {
      title: "题目难度",
      dataIndex: "level",
      key: "level",
      search: false,
      width: 240,
      sorter: true,
      align: "center",
      render: (text) => {
        const level = text;
        const levelMap = {
          1: { label: "简单", color: "green" },
          2: { label: "中等", color: "orange" },
          3: { label: "困难", color: "red" },
        };
        // @ts-ignore
        const { label, color } = levelMap[level] || {
          label: "未知",
          color: "gray",
        };

        return (
          <Tag
            color={color}
            style={{
              minWidth: 60,
              textAlign: "center",
              borderRadius: 12,
              fontWeight: 500,
            }}
          >
            {label}
          </Tag>
        );
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      width: 240,
      search: false,
      sorter: true,
      align: "center",
      render: (text) => (
        <span style={{ color: "#52c41a" }}>
          {" "}
          {dayjs(text).format("YYYY-MM-DD")}
        </span>
      ),
    },
    {
      title: "操作",
      valueType: "option",
      align: "center",
      width: 150,
      render: (_, record) => [
        <a key="edit" onClick={() => showEditModal(record)}>
          编辑
        </a>,
        <a
          key="delete"
          style={{ color: "red" }}
          onClick={() => handleDelete(record)}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<Question>
        actionRef={actionRef}
        columns={columns}
        request={async (params, sort) => {
          try {
            const sortField = Object.keys(sort)?.[0];
            const sortOrder = sort?.[sortField] ?? undefined;
            const res = await listMultiByPageUsingPost({
              current: params.current || 1,
              pageSize: params.pageSize || 10,
              question: params.question as string,
              sortField,
              sortOrder,
              questionBankId: params.questionBankId,
            });

            return {
              // @ts-ignore
              data: res.data?.records || [],
              // @ts-ignore
              total: res.data?.total || 0,
              success: true,
            };
          } catch (error) {
            return { data: [], total: 0, success: false };
          }
        }}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ["10", "20", "50"],
        }}
        search={{
          labelWidth: 100,
          defaultCollapsed: false,
          layout: "horizontal",
        }}
        scroll={{ x: 1500 }}
        headerTitle="题目管理"
        toolBarRender={() => [
          <Button
            type="primary"
            ghost
            key="primary"
            href="/admin/onlineQuestion/ai"
            target="_blank"
          >
            <PlusOutlined /> AI 生成题目
          </Button>,
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={showCreateModal}
          >
            新建题目
          </Button>,
        ]}
      />

      {/* 新建对话框 */}
      <Modal
        title="新建选择题"
        width={800}
        open={createModalVisible}
        onOk={handleCreate}
        onCancel={() => setCreateModalVisible(false)}
        confirmLoading={submitting}
        destroyOnClose
      >
        <Form form={createForm} {...formItemLayout}>
          <Form.Item
            label="题目内容"
            name="question"
            rules={[{ required: true, message: "请输入题目内容" }]}
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入题目描述"
              showCount
              maxLength={500}
            />
          </Form.Item>

          <Form.Item
            label="所属题库"
            name="questionBankId"
            rules={[{ required: true, message: "请选择题库" }]}
          >
            <Select
              options={questionBanks.map((bank) => ({
                label: bank.title,
                value: bank.id,
              }))}
              placeholder="请选择所属题库"
              showSearch
              optionFilterProp="label"
            />
          </Form.Item>

          <Form.Item
            label="正确答案"
            name="rightAnswer"
            rules={[{ required: true, message: "请选择正确答案" }]}
          >
            <Select placeholder="请选择正确选项">
              {["A", "B", "C", "D"].map((option) => (
                <Select.Option key={option} value={option}>
                  选项 {option}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="答案解析"
            name="analysis"
            rules={[{ required: true, message: "请输入答案解析" }]}
          >
            <Input.TextArea
              rows={2}
              placeholder="请输入题目解析"
              showCount
              maxLength={300}
            />
          </Form.Item>

          <div
            style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}
          >
            {["A", "B", "C", "D"].map((option) => (
              <Form.Item
                key={option}
                label={`选项 ${option}`}
                name={`answer${option}`}
                rules={[{ required: true, message: `请输入选项${option}` }]}
              >
                <Input placeholder={`请输入选项${option}内容`} />
              </Form.Item>
            ))}
          </div>

          <div style={{ display: "flex", gap: 16 }}>
            <Form.Item
              label="题目分值"
              name="score"
              rules={[
                { required: true, message: "请输入分值" },
                { pattern: /^[1-9]\d*$/, message: "请输入有效正整数" },
              ]}
              style={{ flex: 1 }}
            >
              <Input type="number" placeholder="请输入题目分值" />
            </Form.Item>

            <Form.Item
              label="难度等级"
              name="level"
              rules={[{ required: true, message: "请选择难度" }]}
              style={{ flex: 1 }}
            >
              <Select placeholder="请选择难度等级">
                <Select.Option value="1">简单</Select.Option>
                <Select.Option value="2">中等</Select.Option>
                <Select.Option value="3">困难</Select.Option>
              </Select>
            </Form.Item>
          </div>
        </Form>
      </Modal>

      {/* 编辑对话框 */}
      <Modal
        title="编辑选择题"
        width={800}
        open={editModalVisible}
        onOk={handleEdit}
        onCancel={() => setEditModalVisible(false)}
        confirmLoading={submitting}
        destroyOnClose
      >
        <Form form={editForm} {...formItemLayout}>
          <Form.Item
            label="题目内容"
            name="question"
            rules={[{ required: true, message: "请输入题目内容" }]}
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入题目描述"
              showCount
              maxLength={500}
            />
          </Form.Item>

          <Form.Item
            label="所属题库"
            name="questionBankId"
            rules={[{ required: true, message: "请选择题库" }]}
          >
            <Select
              options={questionBanks.map((bank) => ({
                label: bank.title,
                value: bank.id,
              }))}
              placeholder="请选择所属题库"
              showSearch
              optionFilterProp="label"
            />
          </Form.Item>

          <Form.Item
            label="正确答案"
            name="rightAnswer"
            rules={[{ required: true, message: "请选择正确答案" }]}
          >
            <Select placeholder="请选择正确选项">
              {["A", "B", "C", "D"].map((option) => (
                <Select.Option key={option} value={option}>
                  选项 {option}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="答案解析"
            name="analysis"
            rules={[{ required: true, message: "请输入答案解析" }]}
          >
            <Input.TextArea
              rows={2}
              placeholder="请输入题目解析"
              showCount
              maxLength={300}
            />
          </Form.Item>

          <div
            style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}
          >
            {["A", "B", "C", "D"].map((option) => (
              <Form.Item
                key={option}
                label={`选项 ${option}`}
                name={`answer${option}`}
                rules={[{ required: true, message: `请输入选项${option}` }]}
              >
                <Input placeholder={`请输入选项${option}内容`} />
              </Form.Item>
            ))}
          </div>

          <div style={{ display: "flex", gap: 16 }}>
            <Form.Item
              label="题目分值"
              name="score"
              rules={[
                { required: true, message: "请输入分值" },
                { pattern: /^[1-9]\d*$/, message: "请输入有效正整数" },
              ]}
              style={{ flex: 1 }}
            >
              <Input type="number" placeholder="请输入题目分值" />
            </Form.Item>

            <Form.Item
              label="难度等级"
              name="level"
              rules={[{ required: true, message: "请选择难度" }]}
              style={{ flex: 1 }}
            >
              <Select placeholder="请选择难度等级">
                <Select.Option value="1">简单</Select.Option>
                <Select.Option value="2">中等</Select.Option>
                <Select.Option value="3">困难</Select.Option>
              </Select>
            </Form.Item>
          </div>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default OnlineQuestionAdminPage;
